package com.pn.controller;

import com.google.code.kaptcha.Producer;
import com.pn.entity.*;
import com.pn.service.AuthService;
import com.pn.service.UserService;
import com.pn.utils.DigestUtil;
import com.pn.utils.TokenUtils;
import com.pn.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {
    @Autowired
    private Producer producer;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserService userService;
    @Resource
    private TokenUtils tokenUtils;
    @Resource
    private AuthService authService;

    @RequestMapping("/captcha/captchaImage")
    public void captchaImage(HttpServletResponse response){
        ServletOutputStream outputStream = null;
        try {
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        //设置验证码的生存时间为30min
        stringRedisTemplate.opsForValue().set(text,"",30*60, TimeUnit.SECONDS);
        response.setContentType("image/jpeg");
        outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }

    @RequestMapping("/login")
    public Result login(@RequestBody LoginUser loginUser){
        if(!stringRedisTemplate.hasKey(loginUser.getVerificationCode())){
            return Result.err(405,"验证码错误！");
        }
        User user = userService.selectUserByUserCode(loginUser.getUserCode());
        String password = DigestUtil.hmacSign(loginUser.getUserPwd());
        if (user != null) {
                if (password.equals(user.getUserPwd())) {
                    if (user.getUserState().equals(WarehouseConstants.USER_STATE_PASS)) {
                        if (Integer.valueOf(user.getIsDelete()) != 1) {
                            //生成token
                            String token = tokenUtils.loginSign(new CurrentUser(user.getUserId(), user.getUserCode(), user.getUserName()), user.getUserPwd());
                            return Result.ok("登录成功！",token);
                        } else {
                            return Result.err(404, "该用户已注销!");
                        }
                    } else {
                        return Result.err(403, "该用户未注册!");
                    }
                    }else {
                    return Result.err(402,"该用户密码错误!");
                    }
                }else {
                    return Result.err(401,"用户名错误!");
                }
    }
    @RequestMapping("/curr-user")
    public Result currentUser(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)String token){
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        return Result.ok(currentUser);
    }
    @RequestMapping("/user/auth-list")
    public Result loadAuthTree(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)String token){
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int userId = currentUser.getUserId();
        List<Auth> authTree = authService.findAuthTreeByUid(userId);
        return Result.ok(authTree);
    }
    @RequestMapping("/logout")
    public Result logout(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)String token){
        stringRedisTemplate.delete(token);
        return Result.ok("退出系统！");

    }












}
